package com.situ.staff.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public final class Upload {

	public static Map<String, Object> upload(HttpServletRequest request) throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(request);
		List<String> names = new ArrayList<String>();
		Map<String, Object> map = new HashMap<String, Object>();
//		int i =1;
		for (FileItem item : items) {
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString();
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
				map.put(name, value);
			} else {
				String fn = getFName(item);
				FileOutputStream fw = new FileOutputStream(getFPath() + "/" + fn);// 注意这里的路径拼接，要有斜杠
				byte[] b = new byte[1024 * 1024];
				int length = -1;
				InputStream is = item.getInputStream();
				while (-1 != (length = is.read(b))) {
					fw.write(b, 0, length);
				}
				fw.flush();
				fw.close();
				is.close();
				names.add(fn);
//				request.setAttribute("fn"+i++, "/images/"+fn);//images为tomcat中配置的虚拟路径
			}
		}
		map.put("list", names);
		return map;
	}

	private static String getFName(FileItem item) {
		// TODO Auto-generated method stub
		String fn = item.getName();
		fn = UUID.randomUUID().toString() + fn.substring(fn.indexOf("."));

		return fn;
	}

	private static File getFPath() {
		File f = new File("F:/web_workspace/imgs");
		if (!f.exists()) {
			f.mkdir();
		}
		return f;
	}

	public static void delFile(String filename) {
		File f = new File(getFPath() + "/" + filename);
		f.delete();
	}
}
